#!/usr/bin/env python
# encoding: utf-8
__author__ = 'Zjay '
"""
@version: 3.6.3
@author: Zjay 
@license: Apache Licence 
@site: 
@software: PyCharm
@file: package_aiohttp_asyncio.py
@time: 2017/12/8 15:38
"""

# import asyncio
# import aiohttp
# from aiohttp import ClientSession
#
#
# async def hello():
#    async with ClientSession() as session:
#        async with session.get('https://api.github.com/events') as resp:
#            print(await resp.json())
#
#
# loop = asyncio.get_event_loop()
# loop.run_until_complete(hello())
# loop.close()

from aiohttp import web
import asyncio


async def index(request):
    resp = web.Response(body=b'<h1>Hello World!</h1>')
    resp.content_type = 'text/html;charset=utf-8'
    return resp


async def hello(request):
    text = '<h1>hello,%s</h1>' % request.match_info['name']
    resp = web.Response(body=text.encode('utf-8'))
    # 如果不添加content_type，某些严谨的浏览器会把网页当成文件下载，而不是直接显示
    resp.content_type = 'text/html;charset=utf-8'
    return resp


async def init(loop):
    app = web.Application(loop=loop, middlewares={logger1_factory, logger2_factory})
    app.router.add_route('GET', '/index', index)
    app.router.add_route('GET', '/hello/{name}', hello)
    server = await loop.create_server(app.make_handler(), 'localhost', 12345)
    return server


def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(init(loop))
    loop.run_forever()


async def logger1_factory(app, handler):
    async def logger1_handler(request):
        print('i am logger1')
        return await handler(request)

    return logger1_handler


async def logger2_factory(app, handler):
    async def logger2_handler(request):
        print('i am logger2')
        return await handler(request)

    return logger2_handler


if __name__ == '__main__':
    main()
